package com.cheyunkeji.er.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;

import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.base.BaseActivity;

import androidx.fragment.app.FragmentActivity;


public class DialogUtil {
    Context mContext;
    LayoutInflater mLayoutInflater;
    boolean mCanBack = true;

    Dialog mDialog;

    public DialogUtil(Context context, LayoutInflater inflater) {
        this(context, inflater, true);
    }

    public DialogUtil(Context context, LayoutInflater inflater, boolean canBack) {
        mContext = context;
        mLayoutInflater = inflater;
        mCanBack = canBack;

        View layout = mLayoutInflater.inflate(R.layout.er_v_dialog, null);
        mDialog = new Dialog(mContext, R.style.myDialog);
        mDialog.setContentView(layout);
        mDialog.setCancelable(false);
        mDialog.setOnKeyListener(myKeylistener);
        mDialog.setCanceledOnTouchOutside(false);
    }

    public void showDialog() {
        if (mContext instanceof Activity) {
            Activity activity = (Activity) mContext;
            if (activity != null && !activity.isFinishing()) {
                mDialog.show();
            }
        }
    }

    public void stopDialog() {
        if (mContext instanceof Activity) {
            Activity activity = (Activity) mContext;
            if (activity != null && !activity.isFinishing()) {
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
            }
        }
    }

    DialogInterface.OnKeyListener myKeylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                if (mCanBack) {
                    if (mContext instanceof BaseActivity) {
                        MyApplication.getInstance().removeActivity(mContext.getClass());
                    } else if (mContext instanceof FragmentActivity) {
                        MyApplication.getInstance().removeActivity(mContext.getClass());
                    }
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_SEARCH
                    && event.getRepeatCount() == 0) {
                return true;
            } else {
                return false;
            }
        }
    };
}
